package cn.yuhan.simplediary.config;

import cn.yuhan.simplediary.system.entity.User;
import cn.yuhan.simplediary.system.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 自定义 UserDetailsService，实现从数据库加载用户信息
 */
@Service
@RequiredArgsConstructor
public class CustomUserDetailsService implements UserDetailsService {

    private final UserMapper userMapper;

    /**
     * 根据用户名查询用户信息，供 Spring Security 认证使用
     *
     * @param username 用户名
     * @return UserDetails 用户详情对象
     * @throws UsernameNotFoundException 用户不存在时抛出异常
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 使用 MyBatis-Plus 提供的 QueryWrapper 来构造查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);

        // 从数据库查询用户
        User user = userMapper.selectOne(queryWrapper);

        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        // 将查询到的 User 转换为 Spring Security 需要的 UserDetails
        return org.springframework.security.core.userdetails.User.builder()
                .username(user.getUsername())
                .password(user.getPassword())
                // 注意：数据库中 role 字段值是带 ROLE_ 前缀的，如 ROLE_USER 或 ROLE_ADMIN
                .roles(user.getRole().name().replace("ROLE_", ""))
                .disabled(!user.getEnabled()) // 禁用用户无法登录
                .build();
    }
}